
<template>
  <div class="articles">
    <el-card>
      <!-- 搜索表单 -->
      <el-form :inline="true" ref="form" :model="form" label-width="80px">
        <el-form-item label="关键字" prop="keyword">
          <el-input
            v-model="form.keyword"
            placeholder="根据文章标题搜索"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择">
            <el-option label="已启用" value="1"></el-option>
            <el-option label="已禁用" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetFields">清除</el-button>
          <el-button type="primary" @click="search">搜索</el-button>
        </el-form-item>
        <el-button
          class="fr"
          @click="addDialog"
          type="success"
          icon="el-icon-edit"
          >新增技巧</el-button
        >
      </el-form>
      <!-- 共计多少条数据 -->
      <el-alert :title="'数据一共' + counts + '条'" type="info" show-icon>
      </el-alert>
      <!-- 文章列表 -->
      <el-table :data="list" stripe style="width: 100%">
        <el-table-column
          prop="id"
          label="序号"
          width="180"
          type="index"
          :index="pagesize * (page - 1) + 1"
        >
        </el-table-column>
        <el-table-column prop="title" label="文章标题" width="180">
          <template slot-scope="scope">
            {{ scope.row.title }}
            <i
              @click="play(scope.row.videoURL)"
              :class="scope.row.videoURL ? 'el-icon-film' : ''"
            ></i>
          </template>
        </el-table-column>
        <el-table-column prop="visits" label="阅读数"> </el-table-column>
        <el-table-column prop="username" label="录入人"> </el-table-column>
        <el-table-column prop="createTime" label="录入时间">
          <template slot-scope="scope">
            {{ scope.row.createTime | dateFormat("YYYY-mm-dd HH:MM:SS") }}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态">
          <template slot-scope="scope">
            <!-- <i class="el-icon-time"></i> -->
            <span style="margin-left: 10px">{{
              scope.row.state ? "已启用" : "已禁用"
            }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="open(scope.row)">预览</el-button>
            <el-button
              @click="changeState(scope.row.state, scope.row.id)"
              type="text"
              >{{ !scope.row.state ? "启用" : "禁用" }}</el-button
            >
            <el-button
              type="text"
              @click="modDialog(scope.row.id)"
              :disabled="!!scope.row.state"
              >修改</el-button
            >
            <el-button
              type="text"
              @click="delArticle(scope.row.id)"
              :disabled="!!scope.row.state"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" justify="end">
        <el-pagination
          :current-page="page"
          @current-change="currentChange"
          @size-change="sizeChange"
          background
          :page-sizes="[5, 10, 20, 50]"
          :page-size="10"
          layout="prev, pager, next, sizes, jumper"
          :total="counts"
        >
        </el-pagination>
      </el-row>
    </el-card>
    <!-- 视频播放 -->
    <el-dialog
      class="movie"
      :visible.sync="dialogMovieVisible"
      @close="close"
      :show-close="false"
    >
      <i @click="dialogMovieVisible = false" class="el-icon-error"></i>
      <video
        v-if="movie"
        ref="video"
        width="100%"
        height="100%"
        controls
        autoplay="autoplay"
      >
        <source :src="movie" type="video/mp4" />
        您的浏览器不支持Video标签。
      </video>
    </el-dialog>
    <!-- 预览文章弹出框 -->
    <el-dialog
      class="preview"
      :visible.sync="dialogPreviewVisible"
      @close="closePreview"
      :show-close="true"
      title="预览文章"
    >
      <!-- <div ref="preview" v-html="previewData" class="content"></div> -->
      <h2>{{ previewData.title }}</h2>
      <div class="header">
        <span>{{
          previewData.createTime | dateFormat("YYYY-mm-dd HH:MM:SS")
        }}</span>
        <span>{{ previewData.username }}</span>
        <i class="el-icon-view"></i>
        <span>{{ previewData.visits }}</span>
      </div>
      <div class="content" v-html="previewData.articleBody"></div>
    </el-dialog>
    <!-- 修改文章弹出框 -->
    <el-dialog
      title="修改文章"
      :visible.sync="dialogModVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form ref="modform" :rules="rules" :model="modform" label-width="80px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="modform.title"></el-input>
        </el-form-item>
        <el-form-item label="文章内容" prop="articleBody">
          <quill-editor
            v-model="modform.articleBody"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="视频地址">
          <el-input v-model="modform.videoURL"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogModVisible = false">取 消</el-button>
        <el-button type="primary" @click="modArticle">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加文章弹出框 -->
    <el-dialog
      title="添加文章"
      :visible.sync="dialogAddVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form ref="addform" :rules="rules" :model="modform" label-width="80px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="modform.title"></el-input>
        </el-form-item>
        <el-form-item label="文章内容" prop="articleBody">
          <quill-editor
            v-model="modform.articleBody"
            :options="editorOption"
          ></quill-editor>
        </el-form-item>
        <el-form-item label="视频地址" prop="videoURL">
          <el-input v-model="modform.videoURL"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddVisible = false">取 消</el-button>
        <el-button type="primary" @click="addArticle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
/**
 * @author: zhanglei
 * @Date: 2020-11-6 18:12:41
 * @Last Modified by: zhanglei
 * @Last Modified time: 2020-11-7 12:17:40
 * 文章
 */
// 引入日期格式化工具
import dateFormat from '@/utils/dateFormat.js'
// 导入样式
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
// 导入组件
import { quillEditor } from 'vue-quill-editor'
import { list, changeState, detail, remove, update, add } from '@/api/hmmm/articles.js'
export default {
  components: {
    quillEditor
  },
  data () {
    return {
      // 表单验证
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 3, max: 30, message: '长度在 3 到 30 个字符', trigger: 'blur' }
        ],
        articleBody: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      },
      // 富文本配置对象
      editorOption: {
        // 占位配置
        placeholder: '请输入文章内容',
        modules: {
          // 配置工具栏
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            ['blockquote', 'code-block'],
            [{ header: 1 }, { header: 2 }],
            [{ list: 'ordered' }, { list: 'bullet' }],
            [{ indent: '-1' }, { indent: '+1' }],
            ['image']
          ]
        }
      },
      // 预览文章弹出框数据
      previewData: {},
      dialogMovieVisible: false, // 是否显示播放视频
      dialogPreviewVisible: false, // 是否显示文章预览
      dialogModVisible: false, // 修改文章弹出框
      dialogAddVisible: false,
      movie: '', // 视频连接地址
      page: 1,
      pagesize: 10,
      counts: 0,
      // 表单数据
      form: {
        keyword: '',
        status: null
      },
      // 文章列表数据
      list: [],
      // 修改文章
      modform: {
        id: '',
        title: '',
        articleBody: '',
        videoURL: ''
      }
    }
  },
  created () {
    this.getArticles()
  },
  filters: {
    dateFormat (val, format) {
      const date = new Date(val)
      return dateFormat(format, date)
    }
  },
  methods: {
    // 删除文章
    delArticle  (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const res = await remove({
            id
          })
          console.log(res)
          this.$message.success('删除成功')
          this.getArticles()
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 添加文章
    addArticle () {
      let flag
      this.$refs.addform.validate((valid) => {
        flag = valid
      })
      if (!flag) return
      try {
        const res = add(this.modform)
        console.log(res)
        this.$message.success('添加成功')
        this.getArticles()
        this.dialogAddVisible = false
      } catch (error) {
        this.$message.error('添加失败')
        this.dialogAddVisible = false
      }
    },
    // 添加文章弹框
    async addDialog () {
      this.dialogAddVisible = true
      if (!this.$refs.addform) return
      this.$refs.addform.resetFields()
    },
    // 修改文章
    async modArticle () {
      let flag
      this.$refs.modform.validate((valid) => {
        flag = valid
      })
      if (!flag) return
      try {
        const res = update(this.modform)
        console.log(res)
        this.$message.success('修改成功')
        this.getArticles()
        this.dialogModVisible = false
      } catch (error) {
        this.$message.error('修改失败')
        this.dialogModVisible = false
      }
    },
    // 修改文章弹出框
    async modDialog (id) {
      this.dialogModVisible = true
      const res = await detail({ id })
      console.log(res)
      this.modform = res.data
    },
    // 关闭修改文章弹框的提示
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    // 切换文章状态
    async changeState (state, id) {
      const data = {}
      data.id = id
      data.state = state ? 0 : 1
      console.log(data)
      this.getArticles()
      try {
        const res = await changeState(data)
        console.log(res)
      } catch (error) {

      }
    },
    // 切换页码, 重新请求数据
    currentChange (currentPage) {
      this.page = currentPage
      this.getArticles()
    },
    sizeChange (pagesize) {
      console.log(pagesize)
      this.pagesize = pagesize
      this.getArticles()
    },
    // 打开预览
    open (row) {
      console.log(row)
      this.dialogPreviewVisible = true
      this.previewData = row
    },
    // 视频播放
    play (url) {
      this.movie = url
      this.dialogMovieVisible = true
    },
    // 视频弹出框关闭
    close () {
      this.movie = ''
    },
    // 关闭预览文章
    closePreview () {

    },
    // 获取文章列表
    async getArticles () {
      const page = this.page
      const pagesize = this.pagesize
      const { keyword, status: state } = this.form
      console.log(state, keyword)
      try {
        const res = await list({
          page,
          pagesize,
          keyword,
          state
        })
        console.log(res)
        this.list = res.data.items
        this.counts = res.data.counts
      } catch (error) {

      }
    },
    // 搜索按钮方法
    search () {
      this.page = 1
      this.getArticles()
    },
    // 清空表单按钮方法
    resetFields () {
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style scoped lang='less'>
// 总条数组件下边距
.el-alert--info.is-light {
  margin-bottom: 10px;
}
// 分页组件上边距
.el-row--flex.is-justify-end {
  margin-top: 30px;
}
// 预览弹出框
.articles .cell i {
  color: blue;
  font-size: 18px;
}
.articles /deep/ .movie .el-dialog__body {
  padding: 0;
  background-color: transparent;
}
.articles /deep/ .movie .el-dialog__header {
  padding: 0;
}
.articles /deep/ .movie .el-dialog {
  background-color: transparent;
}
.articles /deep/ .movie i {
  content: "";
  position: absolute;
  left: 50%;
  top: -66px;
  transform: translateX(-50%);
  font-size: 66px;
  color: #000;
  opacity: 0.1;
}
.articles /deep/ .movie .el-dialog__body:hover i {
  opacity: 0.6;
}
// 富文本框的样式
// 在父组件中去设置子组件的样式，加上/deep/ 实现穿透功能
/deep/ .ql-editor {
  height: 300px;
}
.fr {
  float: right;
}
/deep/ .el-dialog__footer {
  text-align: right;
}
.articles {
  .preview {
    .el-dialog__body {
      .header {
        span,
        i {
          margin-left: 10px;
        }
      }
      .content {
        margin-top: 10px;
        border-top: 1px dashed #aaa;
        background-color: #eee;
        padding: 10px;
        /deep/ .ql-align-center img {
          width: 100%;
          height: 100%;
        };
      }
    }
  }
}
</style>
